package com.yao.system.interceptor;


import cn.hutool.core.util.StrUtil;
import com.yao.system.entity.dto.UserDTO;
import com.yao.system.util.AppJwtUtil;
import com.yao.system.util.UserContext;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

//    private StringRedisTemplate stringRedisTemplate;
//
//    public LoginInterceptor(StringRedisTemplate stringRedisTemplate) {
//        this.stringRedisTemplate = stringRedisTemplate;
//    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        log.info("===============拦截器====================");
        // 1.获取请求头中的token
        String token = request.getHeader("Authorization");
        if (StrUtil.isBlank(token)) {
            response.setStatus(401);
            log.info("===============拦截器  拦截 没有token====================");
            return false;
        }

        //2.判断token是否有效
        try {
            Claims claims = AppJwtUtil.getClaimsBody(token);
            //判断是否过期
            int result = AppJwtUtil.verifyToken(claims);
            if (result==1 || result==2){
                //response.setStatus(HttpStatus.UNAUTHORIZED.value());
                response.setStatus(401);
                //拦截请求
                log.info("===============拦截器  拦截 token不正确====================");
                return false;
            }
            //Object userId = claims.get("id");
            UserDTO userDTO = new UserDTO();
            userDTO.setId((Long) claims.get("id"));
            userDTO.setName((String) claims.get("name"));
            userDTO.setImage((String) claims.get("image"));
            UserContext.saveUser(userDTO);
            ////存储在header中
            //ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
            //    httpHeaders.add("userId", userId + "");
            //}).build();
            //重置请求
            //exchange.mutate().request(serverHttpRequest);
        } catch (Exception e) {
            response.setStatus(401);
            //拦截请求
            log.info("===============拦截器   拦截====================");
            return false;
        }
        log.info("===============拦截器   放行====================");
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除用户
        UserContext.removeUser();
    }

}
